﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using sgsBase;

namespace TestApp.Account
{
    public partial class Register : SgsPage
    {
		string _continueUrl = "";
        protected override void PageLoad(object sender, EventArgs e)
        {
            //RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
			_continueUrl = Request.QueryString["ReturnUrl"];
        }

		//protected void RegisterUser_OnCreatingUser(object sender, LoginCancelEventArgs e)
		protected void CreateUserButton_Click(object sender, EventArgs e)
		{
			Guid id = Guid.NewGuid();
			id.ToString();

			DbUsrUser uu = new DbUsrUser();

			uu.Descr = UserName.Text; // RegisterUser.UserName;
			uu.Status = 1;
			if (uu.Select())
			{
				AddMessage("The given display name already exists. Please choose another.");
				return;
			}
			uu.ClearValues();
			uu.Email = txEmail.Text;
			uu.Status = 1;
			if (uu.Select())
			{
				AddMessage("This email is already registered. Did you forget your password?");
				return;
			}

			//CreateNewUser();
			// to create a new user:
			// - generate a random confirmation string to send to the user
			// - insert data and confirm into database with status 0
			// - send email to the address provided. 
			uu.LoginId = txEmail.Text;
			uu.Descr = UserName.Text;
			uu.LoginPass = Password.Text;
			uu.Email = txEmail.Text;
			uu.DtCreated = DateTime.Now;
			uu.HashCode = ApplicationHelper.CreateHashCode();
			uu.Status = 0;
			uu.Insert();

			string url = ApplicationHelper.AccountUrl + "cregister.aspx?id=" + uu.HashCode;
			string body = "<h2>Welcome to SERS!</h2><p>Please validate your registration by clicking on the link below:</p>";
			body += "<p> <a href='" + url + "'>" + url + "</a></p>";

			string fullbody = Email.BuildWithTemplate(body); //, "..\\MailTemplate.htm");

			Email.Send(uu.Email, "Registration Completion: " + ApplicationHelper.SiteTitle, fullbody);
			AddMessage("Please check your email in order to complete registraion.");
			txEmail.Text = "";
			UserName.Text = "";
			Password.Text = "";
			ConfirmPassword.Text = "";
		}



        protected void RegisterUser_CreatedUser(object sender, EventArgs e)
        {
			FormsAuthentication.SetAuthCookie(UserName.Text, false /* createPersistentCookie */);

            string continueUrl = _continueUrl;
            if (String.IsNullOrEmpty(continueUrl))
            {
                continueUrl = "~/";
            }
            Response.Redirect(continueUrl);
        }

    }
}
